<template>
  <div class="main">
    <a-icon class="QRcodeIcon" :component="allIcon.QRcodeIcon"/>
    <a-form-model ref="form" class="user-layout-login" :model="form" :rules="rules">
      <a-tabs :activeKey="form.type" @change="loginTabChange" style="margin-top:15px;">
        <a-tab-pane :key="1" tab="账号密码">
          <a-form-model-item prop="username">
            <a-input v-model="form.username" size="large" placeholder="账户" >
              <a-icon slot="prefix" type="user" :style="{ color: 'rgba(0,0,0,.25)'}"/>
            </a-input>
          </a-form-model-item>
          <a-form-model-item prop="password">
            <a-input-password v-model="form.password" size="large" placeholder="密码">
              <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }"/>
            </a-input-password>
          </a-form-model-item>
        </a-tab-pane>
        <a-tab-pane :key="2" tab="手机号">
          <a-row :gutter="16">
            <a-col class="gutter-row" :span="24">
              <a-form-model-item prop="mobile">
                <a-input v-model="form.mobile" size="large" placeholder="手机号码" >
                  <a-icon slot="prefix" type="mobile" :style="{ color: 'rgba(0,0,0,.25)'}"/>
                </a-input>
              </a-form-model-item>
            </a-col>
            <a-col class="gutter-row" :span="16">
              <a-form-model-item prop="mobileCode">
                <a-input v-model="form.mobileCode" size="large" type="text" autocomplete="off" placeholder="验证码">
                  <a-icon slot="prefix" :component="allIcon.validCodeIcon" :style="{ color: 'rgba(0,0,0,.25)' }"/>
                </a-input>
              </a-form-model-item>
            </a-col>
            <a-col class="gutter-row" :span="8">
              <a-button style="height:40px;line-height:40px;width:100%" :disabled="state.mobileCaptchaSendBtn" @click.stop.prevent="getCaptchaMobile" v-text="!state.mobileCaptchaSendBtn && '获取验证码'||(state.time+' s')"></a-button>
            </a-col>
          </a-row>
        </a-tab-pane>
        <a-tab-pane :key="3" tab="电子邮箱">
          <a-row :gutter="16">
            <a-col class="gutter-row" :span="24">
              <a-form-model-item prop="email">
                <a-input v-model="form.email" size="large" placeholder="电子邮箱" >
                  <a-icon slot="prefix" type="mail" :style="{ color: 'rgba(0,0,0,.25)'}"/>
                </a-input>
              </a-form-model-item>
            </a-col>
            <a-col class="gutter-row" :span="16">
              <a-form-model-item prop="emailCode">
                <a-input v-model="form.emailCode" size="large" type="text" autocomplete="off" placeholder="验证码">
                  <a-icon slot="prefix" :component="allIcon.validCodeIcon" :style="{ color: 'rgba(0,0,0,.25)' }"/>
                </a-input>
              </a-form-model-item>
            </a-col>
            <a-col class="gutter-row" :span="8">
              <a-button style="height:40px;line-height:40px;width:100%" :disabled="state.emailCaptchaSendBtn" @click.stop.prevent="getCaptchaEmail" v-text="!state.emailCaptchaSendBtn && '获取验证码'||(state.time+' s')"></a-button>
            </a-col>
          </a-row>
        </a-tab-pane>
      </a-tabs>
      <a-row :gutter="16" v-if="captchaOnOff">
        <a-col class="gutter-row" :span="16">
          <a-form-model-item prop="captchaCode">
            <a-input v-model="form.captchaCode" size="large" type="text" autocomplete="off" placeholder="验证码">
              <a-icon slot="prefix" type="security-scan" :style="{ color: 'rgba(0,0,0,.25)' }"/>
            </a-input>
          </a-form-model-item>
        </a-col>
        <a-col class="gutter-row" :span="8">
          <img class="getCaptcha" :src="captchaImageSrc" @click="getCaptchaImage">
        </a-col>
      </a-row>
      <a-form-item>
        <a-checkbox v-model="form.rememberMe" style="line-height: 30px;">记住我</a-checkbox>
        <div style="float:right;line-height:30px;">
          <span>还没有账号？</span>
          <router-link to="/user/register">立即注册</router-link>
          <router-link to="/user/password" style="margin-left:10px">忘记密码</router-link>
        </div>
      </a-form-item>
      <a-form-item style="margin-top:80px">
        <a-button size="large" type="primary" htmlType="submit" class="login-button" :loading="logining" :disabled="logining" @click="handleSubmit">登录</a-button>
      </a-form-item>
      <a-space>
        <div style="margin-top: -10px;">其它登录方式</div>
        <div class="icons-list">
          <a-icon class="dingtalk" :component="allIcon.dingtalkIcon"/>
          <a-icon class="WeChat" :component="allIcon.WeChatIcon"/>
          <a-icon class="Alipay" :component="allIcon.AlipayIcon"/>
          <a-icon class="Sina" :component="allIcon.SinaIcon"/>
        </div>
      </a-space>
    </a-form-model>
  </div>
</template>

<script>

import storage from 'store'
import { mapActions } from 'vuex'
import { timeFix, randomUUID } from '@/utils/util'
import { checkUsername, checkMobile, checkEmail } from '@/utils/rules'
import { getAction, postAction } from '@/api/manage'
import allIcon from '@/core/icons'

export default {
  name: 'Login',
  components: {
    allIcon
  },
  data () {
    let form = {
      type: 1,
      captchaCode: undefined,
      uuid: randomUUID(),
      username: '',
      password: '',
      mobile: '',
      email: '',
      rememberMe: !!storage.get('rememberMe')
    }
    if(form.rememberMe) {
      form.username = storage.get('login_username')
      form.password = storage.get('login_password')
    }
    return {
      allIcon,
      captchaImageSrc: '',
      form: form,
      state: {
        time: 60,
        mobileCaptchaSendBtn: false,
        emailCaptchaSendBtn: false,
        type: 'LOGIN'
      },
      // 验证码开关
      captchaOnOff: true,
      rules: {
        username: [{ required: true, message: '请输入帐户名', trigger: 'blur' }, {validator: checkUsername, trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        captchaCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
        mobile: [{ required: true, message: '请输入手机号', trigger: 'blur' }, { validator: checkMobile, trigger: 'blur' }],
        mobileCode: [{ required: true, message: '请输入手机验证码', trigger: 'blur' }],
        email: [{ required: true, message: '请输入电子邮箱', trigger: 'blur' }, { validator: checkEmail, trigger: 'blur' }],
        emailCode: [{ required: true, message: '请输入电子邮箱验证码', trigger: 'blur' }],
      },
      logining: false,
      url: {
        captchaImage: '/captchaImage',
        captchaMobile: '/captchaMobile'
      }
    }
  },
  created () {
    this.getCaptchaImage()
  },
  methods: {
    getCaptchaImage () {
      let params = {
        uuid: this.form.uuid,
        type: this.state.type
      }
      getAction(this.url.captchaImage, params).then(res => {
        if(res.code == 200){
          this.captchaOnOff = !!res.data.captchaOnOff
          if (this.captchaOnOff) {
            this.captchaImageSrc = 'data:image/gif;base64,' + res.data.img
          }
        }
      })
    },
    getCaptchaMobile () {
      this.$refs.form.validateField(['mobile'], error => {
        if (!error) {
          this.state.mobileCaptchaSendBtn = true;
          let interval = window.setInterval(() => {
            if (this.state.time-- <= 0) {
              this.state.time = 60;
              this.state.mobileCaptchaSendBtn = false;
              window.clearInterval(interval);
            }
          }, 1000);
          const hide = this.$message.loading('验证码发送中..', 0);
          const params = {
            mobile: this.form.mobile,
            type: this.state.type,
            uuid: this.form.uuid
          }
          postAction("/captchaMobile", params).then((res) => {
            if (!res.success) {
              this.requestFailed(res.message);
              setTimeout(hide, 0);
            }
            setTimeout(hide, 500);
          }).catch(err => {
            setTimeout(hide, 1);
            clearInterval(interval);
            this.state.time = 60;
            this.state.mobileCaptchaSendBtn = false;
            this.requestFailed(err);
          });
        }
      })
    },
    getCaptchaEmail () {
      this.$refs.form.validateField(['email'], error => {
        if (!error) {
          this.state.emailCaptchaSendBtn = true;
          let interval = window.setInterval(() => {
            if (this.state.time-- <= 0) {
              this.state.time = 60;
              this.state.emailCaptchaSendBtn = false;
              window.clearInterval(interval);
            }
          }, 1000);
          const hide = this.$message.loading('验证码发送中..', 0);
          const params = {
            email: this.form.email,
            type: this.state.type,
            uuid: this.form.uuid
          }
          postAction("/captchaMobile", params).then((res) => {
            if (!res.success) {
              this.requestFailed(res.message);
              setTimeout(hide, 0);
            }
            setTimeout(hide, 500);
          }).catch(err => {
            setTimeout(hide, 1);
            clearInterval(interval);
            this.state.time = 60;
            this.state.emailCaptchaSendBtn = false;
            this.requestFailed(err);
          });
        }
      })
    },
    loginTabChange(activeKey) {
      this.form.type = activeKey
      this.$refs.form.resetFields()
    },
    ...mapActions(['Login']),
    handleSubmit () {
      // 关闭登录过期的提示框
      this.logining = true
      this.$refs.form.validate(valid => {
        if (valid) {
          this.Login(this.form)
            .then((res) => this.loginSuccess(res))
            .catch(err => this.loginFailed(err))
            .finally(() => {
              this.logining = false
            })
        } else {
          this.logining = false
          if (this.captchaOnOff) {
            this.getCaptchaImage()
          }
        }
      })
    },
    loginSuccess (res) {
      storage.set('rememberMe', this.form.rememberMe)
      if(this.form.rememberMe) {
        storage.set('login_username', this.form.username)
        storage.set('login_password', this.form.password)
      } else {
        storage.remove('login_username')
        storage.remove('login_password')
      }
      this.$router.push({ path: '/' })
      setTimeout(() => {
        this.$notification.success({
          message: '欢迎',
          description: `${timeFix()}，欢迎回来`
        })
      }, 1000)
    },
    loginFailed (err) {
      this.$refs.form.resetFields()
      this.getCaptchaImage()
      this.$message.error(err)
    }
  }
}
</script>

<style lang="less" scoped>
  .QRcodeIcon{
    position: absolute;
    right:0;
    font-size: 32px;
    color: #1890ff;
    margin-top:5px;
    margin-right:5px;
  }
  .ant-space-align-center{
    color:#8f959e;
    line-height: 30px;
    height: 30px;
  }
  .user-layout-login label{
    font-size: 12px!important;
  }
  .user-layout-login {
    label {
      font-size: 14px;
    }
    .ant-page-header{
      padding:20px 0 15px 0;
    }
    .getCaptcha {
      display: block;
      width: 100%;
      height: 40px;
    }

    button.login-button {
      padding: 0 15px;
      font-size: 16px;
      height: 40px;
      width: 100%;
      border-radius: 4px;
    }
    .icons-list{
      .anticon {
        font-size: 30px;
        width: 40px;
      }
      .dingtalk{
        color: #0089FF;
      }
      .WeChat{
        color: #51C332;
      }
      .Alipay{
        color: #06B4FD;
      }
      .Sina{
        color: #D81E06;
      }
    }
  }

</style>
